package com.wedo.mall.activity.goods;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.e.library.widget.EBadgeView;
import com.wedo.mall.R;
import com.wedo.mall.WApp;
import com.wedo.mall.activity.MainActivity;
import com.wedo.mall.activity.agent.AgentDetailActivity;
import com.wedo.mall.activity.chat.ConsultActivity;
import com.wedo.mall.activity.comment.CommentActivity;
import com.wedo.mall.activity.comment.ImageActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.activity.order.OrderActivity;
import com.wedo.mall.adapter.SimilarAdapter;
import com.wedo.mall.dialog.ConsultDialog;
import com.wedo.mall.dialog.ShareDialog;
import com.wedo.mall.entity.Agent;
import com.wedo.mall.entity.AttrItem;
import com.wedo.mall.entity.Comment;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.Shopping;
import com.wedo.mall.fragment.AttrFragment;
import com.wedo.mall.util.DateUtils;
import com.wedo.mall.util.WUrl;
import com.wedo.mall.util.WUtils;
import com.wedo.mall.widget.EWebView;
import com.wedo.mall.widget.GoodsBanner;
import com.wedo.mall.widget.GridImage;
import com.wedo.mall.widget.StarView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 商品详情
 * Created by e on 2017/7/6.
 */

public class GoodsDetailActivity extends EActivity {

    public static final String EXTRA_GOODS_ID = "goods_id";

    private EBadgeView eBadgeView;
    @BindView(R.id.iv_shopping) ImageView iv_shopping;

    @BindView(R.id.cb_banner) ConvenientBanner cb_banner;
    @BindView(R.id.iv_auth) ImageView iv_auth;
    @BindView(R.id.tv_goods) TextView tv_goods;
    @BindView(R.id.iv_collection) ImageView iv_collection;
    @BindView(R.id.tv_intro) TextView tv_intro;
    @BindView(R.id.tv_price) TextView tv_price;
    @BindView(R.id.tv_sale) TextView tv_sale;
    @BindView(R.id.tv_attr) TextView tv_attr;
    @BindView(R.id.btn_auth) Button btn_auth;
    @BindView(R.id.btn_deliver) Button btn_deliver;
    @BindView(R.id.ll_web) LinearLayout ll_web;
    private EWebView eWebView;

    /**店铺信息*/
    @BindView(R.id.iv_img) ImageView iv_img;
    @BindView(R.id.tv_name) TextView tv_agent_name;
    @BindView(R.id.tv_distance) TextView tv_distance;
    @BindView(R.id.sv_star) StarView sv_star;
    @BindView(R.id.v_divider) View v_divider;

    /**相似商品*/
    @BindView(R.id.rv_similar) RecyclerView rv_similar;

    /**评价*/
    @BindView(R.id.layout_comment) View layout_comment;
    @BindView(R.id.tv_comment) TextView tv_comment;
    @BindView(R.id.tv_comment_empty) TextView tv_comment_empty;
    @BindView(R.id.tv_more) TextView tv_more;
    @BindView(R.id.iv_comment_img) ImageView iv_comment_img;
    @BindView(R.id.tv_comment_nickname) TextView tv_comment_nickname;
    @BindView(R.id.sv_comment_star) StarView sv_comment_star;
    @BindView(R.id.tv_comment_context) TextView tv_comment_context;
    @BindView(R.id.gi_comment_image) GridImage gi_image;
    @BindView(R.id.tv_comment_time) TextView tv_comment_time;
    @BindView(R.id.tv_reply_content) TextView tv_reply_content;

    @BindString(R.string.goods_selling) String goods_selling;
    @BindString(R.string.goods_price) String goods_price;
    @BindString(R.string.goods_comment) String goods_comment;
    @BindString(R.string.goods_unit) String goods_unit;
    @BindString(R.string.goods_comment_reply) String goods_comment_reply;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    private Goods goods;
    private EResponse response;
    private Agent agent;
    private String collect_id;

    /**购买相关*/
    private int number = 1;
    private String goodsId;

    public static void toDetail(EActivity activity,String goods_id){
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_GOODS_ID,goods_id);
        activity.toActivity(GoodsDetailActivity.class,bundle);
    }

    @Override
    protected int layout() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        rv_similar.setHasFixedSize(true);
        EViewUtils.horizontal(rv_similar);
        eWebView = new EWebView(ll_web);
        eBadgeView = new EBadgeView(this);
        eBadgeView.setTargetView(iv_shopping);

        String goods_id = getIntent().getStringExtra(EXTRA_GOODS_ID);
        Map<String,String> params = WApp.lngLat();
        params.put(EXTRA_GOODS_ID,goods_id);
        loading();
        post(EApi.GOODS_DETAIL, params, new EObserver() {
            @Override
            public void successful(EResponse response) {
                try {
                    detail(response);
                    dismiss();
                }catch (Exception e){
                    dismiss("数据异常");
                    defaultFinish();
                }
            }

            @Override
            public void failure(String msg) {
                dismiss();
            }
        });

        shoppingCar();
    }

    @Override
    protected void onStart() {
        super.onStart();
        isCorE();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isCorE();
    }

    private void detail(EResponse response){
        this.response = response;

        /**商品banner*/
        final List<String> images = response.list("goodsImages",String.class);
        cb_banner.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new GoodsBanner();
            }
        },images);

        cb_banner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int i) {
                ImageActivity.images(GoodsDetailActivity.this,new ArrayList<>(images),i);
            }
        });

        /**商品信息*/
        goods = response.object("goodsInfo",Goods.class);
        goodsId = goods.id;//默认购买该商品
        tv_goods.setText(goods.goods_name);
        tv_intro.setText(goods.introduction);

        tv_price.setText(String.format(goods_price,goods.fixPrice()));

        tv_sale.setText(String.format(goods_selling,goods.sale_number,goods.browsing_number));
        btn_auth.setVisibility(goods.auth()? View.VISIBLE:View.GONE);
        iv_auth.setVisibility(goods.auth()?View.VISIBLE:View.GONE);
        //btn_deliver.setVisibility(goods.containsExpress("1")?View.VISIBLE:View.GONE);
        btn_deliver.setText(goods.containsExpress("0")?R.string.goods_delivery_available:R.string.goods_delivery_unavailable);

        List<AttrItem> attrs = response.list("attrList",AttrItem.class);
        toAttr(attrs);

        String commentCount = response.string("commentCount");
        tv_comment.setText(String.format(goods_comment,commentCount));
        String is_collect = response.string("is_collect","0");
        collect_id = response.string("collect_id");
        iv_collection.setSelected(TextUtils.equals("1",is_collect));

        String goodsDesc = response.string("goodsDesc");
        eWebView.data(goodsDesc);

        /**相似商品*/

        List<Goods> similar = response.list("similarGoods",Goods.class);
        if (!EUtils.isEmpty(similar)){
            SimilarAdapter adapter = new SimilarAdapter(this,similar);
            rv_similar.setAdapter(adapter);
            adapter.listener(this);
        }

        /**店铺信息*/
        agent = response.object("agentInfo",Agent.class);
        agent.id =goods.agent_id;//bug fix
        tv_agent_name.setText(agent.agent_name);
        tv_distance.setText(String.format("%skm",agent.distance));
        sv_star.star(agent.star);
        v_divider.setVisibility(View.GONE);
        Glide.with(this).load(WUrl.url(agent.logo)).error(R.drawable.place_holder_agent).placeholder(R.drawable.place_holder_agent).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_img);


        /**评价*/

        List<Comment> comments = response.list("commentList",Comment.class);
        if(!EUtils.isEmpty(comments)){
            tv_more.setVisibility(View.VISIBLE);
            layout_comment.setVisibility(View.VISIBLE);
            tv_comment_empty.setVisibility(View.GONE);
            Comment comment = comments.get(0);

            tv_comment_nickname.setText(comment.nickname);
            tv_comment_context.setText(comment.contain);
            sv_comment_star.star(comment.star);
            gi_image.image(comment.images);
            tv_comment_time.setText(DateUtils.convert(format,comment.add_time));

            String reply = comment.reply_contain;
            if (TextUtils.isEmpty(reply)){
                tv_reply_content.setText("");
                tv_reply_content.setVisibility(View.GONE);
            }else {
                tv_reply_content.setText(String.format(goods_comment_reply,reply));
                tv_reply_content.setVisibility(View.VISIBLE);
            }

            Glide.with(this).load(WUrl.url(comment.headimgurl)).error(R.drawable.ease_default_avatar).placeholder(R.drawable.ease_default_avatar).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_comment_img);

        }else {
            tv_more.setVisibility(View.GONE);
            layout_comment.setVisibility(View.GONE);
            tv_comment_empty.setVisibility(View.VISIBLE);
        }
    }

    private void toAttr(Collection<AttrItem> attrs){
        if(attrs != null && !attrs.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            boolean hasMore = false;
            for (AttrItem attr:attrs){
                sb.append(hasMore?"，":"");
                sb.append(attr.attr_value);
                hasMore = true;
            }
            sb.append("，").append(number).append(goods_unit);
            tv_attr.setText(sb.toString());
        }else {
            tv_attr.setText("");
        }
    }

    /**隐藏属性Fragment*/
    private boolean hideAttr(){
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fl_fragment);
        if(fragment !=null && fragment.isVisible()) {
            getSupportFragmentManager().beginTransaction().hide(fragment).commit();
            return true;
        }
        return false;
    }

    @OnClick(R.id.iv_backward)
    protected void onBackClick(){
        defaultFinish();
    }

    @OnClick(R.id.iv_share)
    protected void onShareClick(){
        ShareDialog.with(this).goods(goods).show();
    }

    @OnClick(R.id.iv_shopping)
    protected void onShoppingCarClick(){
        MainActivity.toShopping(this);
    }

    @OnClick(R.id.iv_collection)
    protected void onCollectionClick(){
        if (iv_collection.isSelected()){
            delCollect();
        }else {
            toCollect();
        }
    }

    private void toCollect(){
        if(!WLogin.isLogged(this)) {
            return;
        }

        String id = goods.id;
        String type = "0";

        loading();
        Observable<EResponse> observable = api().collect(id,type);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                collect_id = response.string("collect_id");
                iv_collection.setSelected(true);
                toast(R.string.goods_collect_success);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    private void delCollect(){
        loading();
        Observable<EResponse> observable = api().delCollect(collect_id);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                iv_collection.setSelected(false);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }


    @OnClick(R.id.tv_attr)
    protected void onAttrClick(){
        toAttrFragment(0);
    }

    private void toAttrFragment(final int buyNow){
        AttrFragment fragment = AttrFragment.with(goods);
        fragment.widget.setOnSelectedAttr(new AttrFragment.OnSelectedAttr() {
            @Override
            public void onSelected(String id, int number, Collection<AttrItem> attrs) {
                GoodsDetailActivity.this.goodsId = id;//选择购买的商品
                GoodsDetailActivity.this.number = number;
                GoodsDetailActivity.this.toAttr(attrs);
                GoodsDetailActivity.this.hideAttr();

                AddShoppingCar(buyNow);
            }
        });

        getSupportFragmentManager()
                .beginTransaction().addToBackStack(null)
                .replace(R.id.fl_fragment, fragment).commit();
    }

    /**查看更多评价*/
    @OnClick(R.id.tv_more)
    protected void onMoreClick(){
        CommentActivity.toComment(this,goods.id);
    }

    @OnClick(R.id.iv_img)
    protected void onAgentClick(){
        AgentDetailActivity.toDetail(this,goods.agent_id);
    }


    @OnClick(R.id.ll_consult)
    protected void onConsultClick(){
        ConsultDialog dialog = ConsultDialog.with(this);
        dialog.listener = new ConsultDialog.OnConsultListener() {
            @Override
            public void onConsult(int type) {
                if(type == ConsultDialog.CONSULT_PHONE) {
                    WUtils.requestPhoneCall(GoodsDetailActivity.this,agent.agent_phone);
                }else {
                    //环信聊天
                    toConsultActivity();
                }
            }
        };

        dialog.show();
    }

    /**环信聊天*/
    private void toConsultActivity(){
        if(!WLogin.isLogged(this)) {
            return;
        }
        ConsultActivity.toConsult(this,agent);
    }

    @OnClick(R.id.btn_add_shopping_car)
    protected void onAddShoppingCar(){

        if(!goods.payable()) {
            /**线下支付*/
            WUtils.showTipsDialog(this);
            return;
        }

        if(WLogin.isLogged(this)) {
            toAttrFragment(0);
            //AddShoppingCar();
        }
    }

    @OnClick(R.id.btn_buy_now)
    protected void onBuynowClick(){
        if(WLogin.isLogged(this)) {
//            toAttrFragment(1);
            buynow();
        }
    }

    /**加入购物车*/
    private void AddShoppingCar(){
        AddShoppingCar(0);
    }

    /**立即购买*/
    private void buynow(){
        AddShoppingCar(1);
    }

    private void AddShoppingCar(final int isBuy){
        if (!WLogin.isBinding(this)){
            return;
        }

        loading();
        Observable<EResponse> observable = api().addShoppingCar(goodsId,String.valueOf(number),String.valueOf(0));
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {

                if(isBuy == 0) {
                    //购物车显示数量
                    dismiss();
                    int count = eBadgeView.getBadgeCount() + number;
                    eBadgeView.setBadgeCount(count);
                    toast(R.string.goods_add_to_car_successful);

                }else {
                    //跳转到支付页面
                    toOrderActivity();
                }

            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    private void shoppingCar(){
        if(!WLogin.logged(this)) {
            return;
        }

        EClient.with().post(EApi.SHOPPING_CAR, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Shopping> list = response.list(Shopping.class);
                int number = WUtils.goodsNumber(list);
                eBadgeView.setBadgeCount(number);
            }

            @Override
            public void failure(String msg) {
                eBadgeView.setBadgeCount(0);
            }
        });
    }

    /**立即购买，跳转到确认订单页面*/
    private void toOrderActivity(){
        EClient.with().post(EApi.SHOPPING_CAR, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                List<Shopping> list = response.list(Shopping.class);
                if (EUtils.isEmpty(list)){
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("orders",(ArrayList<? extends Parcelable>) list);
                toActivity(OrderActivity.class,bundle);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        eWebView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if(!this.hideAttr()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == WUtils.REQ_PHONE_CALL) {
            if(grantResults.length >0) {
                WUtils.phoneCall(GoodsDetailActivity.this,agent.agent_phone);
            }
        }
    }
}
